<?php
// +----------------------------------------------------------------------
// | 知识星球[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 abcblockchain.io
// +----------------------------------------------------------------------
// | 后台管理使用了HisiPHP
// +----------------------------------------------------------------------
// | Author: abcblockchain.io
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\Db;

/**
 * Token模型
 * @package app\common\model
 */
class Redpacket extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'ctime';
    protected $updateTime = false;

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;


    /**
     * 创建红包
     * @author
     * @param $userId
     * @param $money
     * @param $num
     * @param $type
     * @param $content
     * @param $currencyId
     * @return bool|string
     */
    public function createRedPacket($userId, $money, $num, $type, $content, $currencyId)
    {
        $insertData = [];
        $code = dechex(rand(100, 999999)) . uniqid();
        $insertData['code'] = $code;
        $insertData['user_id'] = $userId;
        $insertData['money'] = $money;
        $insertData['num'] = $num;
        $insertData['type'] = $type;
        $insertData['content'] = $content;
        $insertData['ctime'] = time();
        Db::startTrans();
        try {
            $redRes = $this->insert($insertData);
            Db::name('users_currency')->where('user_id', $userId)->where('currency_id', $currencyId)->setDec('num', $money);
            DB::commit();
        } catch (\Exception $e) {
            return false;
        }
        if ($redRes) {
            return $code;
        } else {
            return false;
        }

    }

    /**
     * 我创建的红包
     * @author
     * @param $userId
     * @param int $startNo
     * @param int $limit
     * @return array
     */
    public function myRedPacket($userId,$startNo = 0, $limit = 10){
        $map = [];
        $map['user_id'] = $userId;
        $map['status'] = 1;
        $countMy = $this->where($map)->count('id');
        $startNo = $startNo * $limit;
        $redList = $this->field('id,money,num,getmoney,getnum,content,type,ctime')->where($map)->limit($startNo, $limit)->order('ctime desc')->select();
        $data = [];
        $data['count'] = $countMy ? $countMy : 0;
        $data['redList'] = $redList ? $redList : [];
        return $data;

    }

    /**
     * 红包信息
     * @author
     * @param $redId
     * @return array|false|\PDOStatement|string|Model
     */
    public function redInfo($redId){
        $map = [];
        $map['id'] = $redId;
        $map['status'] = 1;
        $redInfo = $this->where($map)->find();
        return $redInfo ? $redInfo : [];
    }



}